 package org.mybatis.core.typehandler;
 
 import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.core.jdbc.SQLStatement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
 public class BlobStringTypeHandler extends BaseTypeHandler<String>
 {
   protected static final Logger LOG = LoggerFactory.getLogger(BlobStringTypeHandler.class);
   private static String CharacterEncoding = "UTF-8";
 
   public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType)
     throws SQLException
   {
     if (SQLStatement.isEmpty(parameter)) {
       ps.setNull(i, 2004);
     }
     else
     {
       byte[] bytes = null;
       try {
         bytes = parameter.getBytes(CharacterEncoding);
       } catch (UnsupportedEncodingException e) {
         LOG.error(e.getMessage(), e);
       }
       ps.setBlob(i, new ByteArrayInputStream(bytes), bytes.length);
     }
   }
 
   public String getNullableResult(ResultSet rs, String columnName)
     throws SQLException
   {
     return getBlobAsString(rs.getBlob(columnName));
   }
 
   public String getBlobAsString(Blob blob) throws SQLException {
     if (blob == null)
       return null;
     try
     {
       byte[] bytes = blob.getBytes(1L, (int)blob.length());
       if (bytes != null) {
         return CharacterEncoding != null ? new String(bytes, CharacterEncoding) : new String(bytes);
       }
       return null;
     }
     catch (UnsupportedEncodingException e) {
       LOG.error(e.getMessage(), e);
     }
     return null;
   }
 
   public String getNullableResult(ResultSet rs, int columnIndex)
     throws SQLException
   {
     return getBlobAsString(rs.getBlob(columnIndex));
   }
 
   public String getNullableResult(CallableStatement cs, int columnIndex)
     throws SQLException
   {
     return getBlobAsString(cs.getBlob(columnIndex));
   }
 }

